﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace Utilities
{
    public static class Tools
    {
        /// <summary>
        /// 将指定对象obj序列化到文件fn中
        /// </summary>
        /// <param name="fn">文件路径</param>
        /// <param name="obj">对象</param>
        public static void Serialize(string fn, object obj)
        {
            BinaryFormatter bf = new BinaryFormatter();
            using (FileStream fs = new FileStream(fn, FileMode.OpenOrCreate, FileAccess.Write))
            {
                bf.Serialize(fs, obj);
            }
        }
        /// <summary>
        /// 从文件fn中反序列出类型为T的对象
        /// </summary>
        /// <typeparam name="T">返回的对象类型</typeparam>
        /// <param name="fn">文件名称</param>
        /// <returns>对象</returns>
        public static T DeSerialize<T>(string fn)
        {
            BinaryFormatter bf = new BinaryFormatter();
            using (FileStream fs = new FileStream(fn, FileMode.OpenOrCreate, FileAccess.Read))
            {
               return (T)bf.Deserialize(fs);
            }
        }
        /// <summary>
        /// 获取指定对象的深度克隆对象
        /// </summary>
        /// <typeparam name="T">被克隆者类型</typeparam>
        /// <param name="obj">被克隆者</param>
        /// <returns>克隆出来的对象</returns>
        public static T Clone<T>(T obj)
        {
            BinaryFormatter bf = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())
            {
                bf.Serialize(ms, obj);
                ms.Position = 0;
                return (T)bf.Deserialize(ms);
            }
        }
    }
}
